//
//  NSString+Ext.m
//  Qilekang
//
//  Created by YULING MINA on 14-7-15.
//  Copyright (c) 2014年 Qilekang. All rights reserved.
//

#import "NSString+Ext.h"
#import "NSData+Ext.h"
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import "GTMBase64.h"
static const char *kBase64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

@implementation NSString (MD5)

+(NSString*)RC4EncodingWithKey:(NSString*)aInput key:(NSString*)aKey
{
    NSMutableArray *iS = [[NSMutableArray alloc] initWithCapacity:256];
    NSMutableArray *iK = [[NSMutableArray alloc] initWithCapacity:256];
    
    for (int i= 0; i<256; i++) {
        [iS addObject:[NSNumber numberWithInt:i]];
    }
    
    int j=1;
    
    for (short i=0; i<256; i++) {
        
        UniChar c = [aKey characterAtIndex:i%aKey.length];
        
        [iK addObject:[NSNumber numberWithChar:c]];
    }
    
    j=0;
    
    for (int i=0; i<255; i++) {
        int is = [[iS objectAtIndex:i] intValue];
        UniChar ik = (UniChar)[[iK objectAtIndex:i] charValue];
        
        j = (j + is + ik)%256;
        NSNumber *temp = [iS objectAtIndex:i];
        [iS replaceObjectAtIndex:i withObject:[iS objectAtIndex:j]];
        [iS replaceObjectAtIndex:j withObject:temp];
        
    }
    
    int i=0;
    j=0;
    
    NSString *result = aInput;
    
    for (short x=0; x<[aInput length]; x++) {
        i = (i+1)%256;
        
        int is = [[iS objectAtIndex:i] intValue];
        j = (j+is)%256;
        
        int is_i = [[iS objectAtIndex:i] intValue];
        int is_j = [[iS objectAtIndex:j] intValue];
        
        int t = (is_i+is_j) % 256;
        int iY = [[iS objectAtIndex:t] intValue];
        
        UniChar ch = (UniChar)[aInput characterAtIndex:x];
        UniChar ch_y = ch^iY;
        
        result = [result stringByReplacingCharactersInRange:NSMakeRange(x, 1) withString:[NSString stringWithCharacters:&ch_y length:1]];
    }
    return result;
}

- (NSString *)MD5EncodingString
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] MD5EncodingString];
}

@end

@implementation NSString (base64)

- (NSString *)base64EncodingString
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] base64EncodingString];
}

@end

@implementation NSString (SHA1)

- (NSData *)HMACSHA1EncodeDataWithKey:(NSString *)key
{
    return [[self dataUsingEncoding:NSUTF8StringEncoding] HMACSHA1EncodeDataWithKey:key];
}

@end

@implementation NSString (url)

- (NSString *)URLEncodingString
{
    return [(NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[[self mutableCopy] autorelease], NULL, CFSTR("=,!$&'()[]*+;@?\n\"<>#\t :/"), kCFStringEncodingUTF8) autorelease];
}

- (NSString *)URLDecodingString
{
    return [(NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)[[self mutableCopy] autorelease], CFSTR(""), kCFStringEncodingUTF8) autorelease];
}

@end

@implementation NSString (Regex)

- (BOOL)isMobileNumber
{
   return [self isMatchedByRegex:@"^1\\d{10}$"];  //一开头的11位数字
}

@end

@implementation NSString (Device)

+ (NSString *)imei
{
    return [[NSString macAddress] MD5EncodingString];
}

+ (NSString *)macAddress
{
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1\n");
        return NULL;
    }
    
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        free(buf);//add by xuanwenchao at 2012.12.04
        printf("Error: sysctl, take 2");
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    
    return outstring;
}

+ (NSString *)convert2ShortTime:(NSTimeInterval)secs;
{
    int oneDaySecs = 24 * 60 * 60;
    NSTimeInterval todaytime = [[NSDate date] timeIntervalSince1970];
    //修正为东八区时间
    int todaytimeDiff = (int)todaytime  % (oneDaySecs) + 8 * 60 * 60;
    NSTimeInterval realtime = secs;
    
    int difftime = todaytime -  realtime;
    
    NSDate * chatDate = [NSDate dateWithTimeIntervalSince1970:secs];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    if(difftime <= todaytimeDiff)
    {
        [formatter setDateFormat:@"今天 HH:mm"];;
    }
    else if(difftime <= todaytimeDiff + oneDaySecs)
    {
        [formatter setDateFormat:@"昨天 HH:mm"];
    }
    else if(difftime <= todaytimeDiff + oneDaySecs * 2)
    {
        [formatter setDateFormat:@"前天 HH:mm"];
    }
    else
    {
        [formatter setDateFormat:@"MM月dd日"];
    }
    NSString *dateStr = [formatter stringFromDate:chatDate];
    return dateStr;
}


- (NSDictionary*)coverDictionary
{
    NSMutableDictionary* dic = [NSMutableDictionary dictionary];
    NSString *str = [self stringByReplacingOccurrencesOfString:@"{" withString:@""];
    NSString *stra = [str stringByReplacingOccurrencesOfString:@"}" withString:@""];
    NSString *newStr = [stra stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    NSArray* arr = [newStr componentsSeparatedByString:@";"];
    for (int i = 0; i < arr.count; i++) {
        NSString* str = [arr objectAtIndex:i];
        NSArray* tempArr = [str componentsSeparatedByString:@"="];
        if (tempArr.count > 1) {
             NSString* key = [tempArr objectAtIndex:0];
             NSString* value = [tempArr objectAtIndex:1];
            [dic setValue:value forKey:key];
        }
    }
    return dic;
}

-(NSString *)__customBase64Encoding
{
    NSDate * date = [NSDate date];
    int32_t seed = [date timeIntervalSince1970]*1000;
    int i = (seed%32);
    
    NSString * str = [NSString stringWithFormat:@"%c%c%c%c%c%@%c%c%c%c%c", kBase64EncodeChars[i],kBase64EncodeChars[i+2],kBase64EncodeChars[i+4],kBase64EncodeChars[i+6],kBase64EncodeChars[i+8], self,kBase64EncodeChars[i+10],kBase64EncodeChars[i+12],kBase64EncodeChars[i+16],kBase64EncodeChars[i+18],kBase64EncodeChars[30]];
    
    NSData * lpData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSData * encodeData = [GTMBase64 encodeData:lpData];
    return [[NSString alloc] initWithData:encodeData encoding:NSUTF8StringEncoding];
}

-(NSString *)customBase64Encoding
{
    return [[self __customBase64Encoding] __customBase64Encoding];
}

+ (NSString *)getDeviceName{
    
    size_t size;
    // get the length of machine name
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    // get machine name
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *correspondVersion = [NSString stringWithFormat:@"%s", machine];
    free(machine);
    
    if ([correspondVersion isEqualToString:@"i386"])        return@"Simulator";
    if ([correspondVersion isEqualToString:@"x86_64"])       return @"Simulator";
    
    if ([correspondVersion isEqualToString:@"iPhone1,1"])   return@"iPhone 1";
    if ([correspondVersion isEqualToString:@"iPhone1,2"])   return@"iPhone 3";
    if ([correspondVersion isEqualToString:@"iPhone2,1"])   return@"iPhone 3S";
    if ([correspondVersion isEqualToString:@"iPhone3,1"] || [correspondVersion isEqualToString:@"iPhone3,2"])   return@"iPhone 4";
    if ([correspondVersion isEqualToString:@"iPhone4,1"])   return@"iPhone 4S";
    if ([correspondVersion isEqualToString:@"iPhone5,1"] || [correspondVersion isEqualToString:@"iPhone5,2"])   return @"iPhone 5";
    if ([correspondVersion isEqualToString:@"iPhone5,3"] || [correspondVersion isEqualToString:@"iPhone5,4"])   return @"iPhone 5C";
    if ([correspondVersion isEqualToString:@"iPhone6,1"] || [correspondVersion isEqualToString:@"iPhone6,2"])   return @"iPhone 5S";
    if ([correspondVersion isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    if ([correspondVersion isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    if ([correspondVersion isEqualToString:@"iPhone8,1"]) return @"iPhone 6s Plus";
    if ([correspondVersion isEqualToString:@"iPhone8,2"]) return @"iPhone 6s";
    if ([correspondVersion isEqualToString:@"iPod1,1"])     return@"iPod Touch 1";
    if ([correspondVersion isEqualToString:@"iPod2,1"])     return@"iPod Touch 2";
    if ([correspondVersion isEqualToString:@"iPod3,1"])     return@"iPod Touch 3";
    if ([correspondVersion isEqualToString:@"iPod4,1"])     return@"iPod Touch 4";
    if ([correspondVersion isEqualToString:@"iPod5,1"])     return@"iPod Touch 5";
    
    if ([correspondVersion isEqualToString:@"iPad1,1"])     return@"iPad 1";
    if ([correspondVersion isEqualToString:@"iPad2,1"] || [correspondVersion isEqualToString:@"iPad2,2"] || [correspondVersion isEqualToString:@"iPad2,3"] || [correspondVersion isEqualToString:@"iPad2,4"])     return@"iPad 2";
    if ([correspondVersion isEqualToString:@"iPad2,5"] || [correspondVersion isEqualToString:@"iPad2,6"] || [correspondVersion isEqualToString:@"iPad2,7"] )      return @"iPad Mini";
    if ([correspondVersion isEqualToString:@"iPad3,1"] || [correspondVersion isEqualToString:@"iPad3,2"] || [correspondVersion isEqualToString:@"iPad3,3"] || [correspondVersion isEqualToString:@"iPad3,4"] || [correspondVersion isEqualToString:@"iPad3,5"] || [correspondVersion isEqualToString:@"iPad3,6"])      return @"iPad 3";
    
    
    return @"iphone";
    
}

+ (NSString *)getCurrentVersion{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}
@end

@implementation NSString (DBPath)

+ (NSString *) userIdExclusiveDirectionWithUserId
{
    return  [self userIdExclusiveDirectionWithUserId:@"1212"];
}


+ (NSString *) userIdExclusiveDirectionWithUserId : (NSString *) userId
{
    NSMutableDictionary * userDic = [NSMutableDictionary dictionary];
    [userDic setObject:userId forKey:@"userId"];
    NSArray * pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [[pathArray objectAtIndex:0] stringByAppendingString:@"QLK"];
    NSString * directorPath = [documentsDirectory stringByAppendingString:userId];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:directorPath])
    {
        [fileManager createDirectoryAtPath:directorPath withIntermediateDirectories:YES attributes:nil error:nil];
        
    }
    return  directorPath ;
}


+(BOOL)isNotEmpty:(NSString*)string{
    return (string !=nil && ![string isKindOfClass:[NSNull class]] && ![@"" isEqualToString:string] && ![@"NULL" isEqualToString:string] && ![@"null" isEqualToString:string]);
}
@end
@implementation NSString (heightOrWidth)
//返回字符串所占用的尺寸.
-(CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

@end


@implementation NSString (attributeString)

- (NSMutableAttributedString* )toAttributeString {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:LABEL_LINE_SPACE];
    
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self length])];
    
    return attributedString;
}


- (NSMutableAttributedString *)getAttributeStringWithMinddleLine{
    NSUInteger length = [self length];
    if (length <= 0) {
        return nil;
    }
    NSMutableAttributedString *attri = [self toAttributeString];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
    [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor colorWithRGB:0x999999] range:NSMakeRange(0, length)];
    return attri;
}

- (NSMutableAttributedString *)getAttributeStringWithBottomLine {
    NSUInteger length = [self length];
    if (length <= 0) {
        return nil;
    }
    NSMutableAttributedString *attri = [self toAttributeString];
    [attri addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
    [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor colorWithRGB:0x999999] range:NSMakeRange(0, length)];
    return attri;
}

@end

@implementation NSString (filePathExt)

- (NSString* )toThumbnail{
    if(self.length != 0){
       return [NSString stringWithFormat:@"%@?s=t",self];
    }else{
       return @"";
    }
}

- (NSString*)trimmingLeadingAndTrailingWhitespace
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
@end

